package com.laiyizhan.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * 读取配置文件工具类
 * 
 * @author huangyuan
 * 
 */
public class Configuration {

	private static Properties defaultProperty;

	private static long lastModified = -1;

	public static Properties getDefaultProperty() {
		return defaultProperty;
	}

	static {
		init();
	}

	private static void init() {
		defaultProperty = new Properties();
		try {
			File file = new File(Configuration.class.getResource("/config.properties").getPath());
			if (file.exists()) {
				if (lastModified == -1) {
					// 初始最后修改时间
					lastModified = file.lastModified();
				}
				// 加载数据
				defaultProperty.load(new FileInputStream(file));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据key获取value
	 * 
	 * @param key
	 * @return
	 */
	public static String getProperty(String key) {
		isReload();
		return defaultProperty.getProperty(key, "");
	}

	/**
	 * 判断是否重新加载配置文件内容
	 */
	private static void isReload() {
		// 重新加载数据
		try {
			File file = new File(Configuration.class.getResource("/config.properties").getPath());
			if (file.exists()) {
				if (file.lastModified() != lastModified) {
					defaultProperty.load(new FileInputStream(file));
					lastModified = file.lastModified();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
